<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Goods;
use Illuminate\Http\Request;
use Excel;
use Illuminate\Support\Facades\DB;
use XS;

class GoodsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $goods = Goods::orderBy('id', 'DESC')->paginate();
        return view('goods.index', compact('goods'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        Goods::destroy($id);
        return redirect()->route('goods.index')->with('success', 'Goods delete successfully');
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function createExcel()
    {
        //
        return view('goods.excel_create');
    }

    /**
     * @param Request $request
     */
    public function storeExcel(Request $request)
    {
        //
        $file = $request->file('goods');

        if (!$file->isValid()) {
            return $file->getError();
        }
        $realPath = $file->getRealPath(); //临时地址

        set_time_limit(0);

        $res = [];
        Excel::load($realPath, function ($reader) use (&$res) {
            $data = $reader->all();
            $res = $reader->toArray();
        });

        $xs = new XS(config_path('Xunsearch.ini'));
        $init = new \XSDocument();

        //分类
        $category = Category::pluck('cate_name')->toArray();
        $categoryArr = [];

        $xs->index->openBuffer();//开启索引缓存
        foreach ($res[0] as $key => $goods) {
            $cate = explode('/',$goods['goods_category']);

            if(!in_array($cate[0],$category)) //如果没在数组里面的话 。。
            {
                $categoryArr[] = [
                    'cate_name'  => $cate[0],
                ];
            }

            $goods['category'] = $cate[0];
            $createGoods = Goods::create($goods);

            $init->setFields([
                'pid' => $createGoods->id,
                'goods_name' => $createGoods->goods_name,
                'shop_name' => $createGoods->shop_name,
                'chrono' => time(),
            ]);
            $xs->index->add($init);// 用数组进行批量赋值
        }
        $xs->index->closeBuffer();//关闭索引缓存

        if($categoryArr)
        {
            $categoryArr = array_unique($categoryArr);
            DB::table('category')->insert($categoryArr);
        }

        return redirect()->route('goods.index')->with('success', 'Goods created successfully');
    }


    //上传错误 删除当天索引的信息
    public function deleteDayUpload()
    {
        set_time_limit(0);

        $start = date('Y-m-d');
        $end = date("Y-m-d", strtotime("+1 day"));
        $goods = Goods::whereBetween('created_at', [$start, $end])->pluck('id')->toArray();

        if(!count($goods))
        {
            return redirect()->route('goods.index')->with('error', 'no Goods');
        }

        $xs = new XS(config_path('Xunsearch.ini'));
        $xs->index->del($goods);

        return redirect()->route('goods.index')->with('success', 'GoodsIndexs delete successfully');
    }

    //删除当天数据
    public function deleteDayData()
    {
        set_time_limit(0);

        $start = date('Y-m-d');
        $end = date("Y-m-d", strtotime("+1 day"));
        $goods = Goods::whereBetween('created_at', [$start, $end])->pluck('id')->toArray();

        if(!count($goods))
        {
            return redirect()->route('goods.index')->with('error', 'no Goods');
        }

        Goods::destroy($goods);

        return redirect()->route('goods.index')->with('success', 'Goods delete successfully');
    }


    //上传错误 更新当天索引信息
    public function updateDayUpload(Request $request)
    {
        set_time_limit(0);

        $start = date('Y-m-d');
        $end = date("Y-m-d", strtotime("+1 day"));
        $goods = Goods::whereBetween('created_at', [$start, $end])->paginate(2000);

        if(!$goods->count())
        {
            return redirect()->route('goods.index')->with('error', 'no Goods');
        }

        $xs = new XS(config_path('Xunsearch.ini'));
        $init = new \XSDocument();

        $xs->index->openBuffer();//开启索引缓存
        foreach ($goods as $key => $value) {
            $init->setFields([
                'pid' => $value->id,
                'goods_name' => $value->goods_name,
                'shop_name' => $value->shop_name,
                'chrono' => time(),
            ]);

            $xs->index->add($init);// 用数组进行批量赋值
        }
        $xs->index->closeBuffer();//关闭索引缓存

        $page = 1;
        if($request->query->has('page') && $request->query->get('page'))
        {
            $page = $request->query->get('page');
        }

        $nextPage = $page + 1;

        echo "<a href='/updateDay?page=$nextPage'> GoodsIndexs Update $page Page successfully ( click Next Page ) <a/>";
    }


    //删除重复商品 并留下最新id的商品
    public function deleteRepeatGoods()
    {
        set_time_limit(0);

        $goods = DB::select(" SELECT id FROM goods WHERE id IN ( SELECT min(id) FROM goods GROUP BY goods_id HAVING count(goods_id) > 1 )");

        $uniqueGoods = [];

        foreach ($goods as $key => $value)
        {
            $uniqueGoods[] = $value->id;
        }

        if(!count($uniqueGoods))
        {
            return 'no Goods';
        }

        $xs = new XS(config_path('Xunsearch.ini'));
        $xs->index->del($uniqueGoods);

        Goods::destroy($uniqueGoods);

        return 'ok';
    }

    //删除优惠券过期商品
    public function deleteExpiredGoods()
    {
        set_time_limit(0);

        $expired = date("Y-m-d", strtotime("-1 day"));
        $goods = Goods::where('coupon_etime' , '<=' , $expired)->pluck('id')->toArray();

        if(!count($goods))
        {
            return 'no Goods';
        }

        $xs = new XS(config_path('Xunsearch.ini'));
        $xs->index->del($goods);

        Goods::destroy($goods);

        return 'ok';
    }

}
